#!/usr/bin/env python
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from dateutil.relativedelta import relativedelta

class StockLot(models.Model):
    _inherit = 'stock.lot'
    
    #  def _check_expiry_date(self):
        #  for record in self:
            #  if record.expiration_date and record.expiration_date <= fields.Date.today():
                #  self.env['expiry.inspection.order'].create({
                    #  'lot_id': record.id,
                    #  'quantity': record.product_qty,
                    #  'source_location': record.location_id.id,
                    #  'inspection_location': self.env.ref('stock.location_inspection').id
                #  })
#
    #  @api.model
    #  def cron_check_expired_lots(self):
        #  expired_lots = self.search([
            #  ('expiration_date', '<=', fields.Date.today()),
            #  ('product_qty', '>', 0)
        #  ])
        #  expired_lots._check_expiry_date()

    # 添加计算字段的依赖关系
    @api.depends('production_date', 'product_id')
    def _compute_expiry_dates(self):
        for lot in self:
            if not lot.production_date or not lot.product_id:
                continue

            product = lot.product_id.product_tmpl_id
            # 计算到期日期（生产日期 + 有效期天数）
            if product.expiration_time:
                expiration_date = fields.Datetime.from_string(lot.production_date) + relativedelta(days=product.expiration_time)
                lot.expiration_date = expiration_date
            else:
                lot.expiration_date = False

            # 计算下架日期（到期日期 - 提前天数）
            if product.removal_time and lot.expiration_date:
                lot.removal_date = expiration_date - relativedelta(days=product.removal_time)
            else:
                lot.removal_date = False

            # 计算使用截止日期（到期日期 - 提前天数，假设字段为use_time）
            if product.use_time and lot.expiration_date:
                lot.use_date = expiration_date - relativedelta(days=product.use_time)
            else:
                lot.use_date = False

            # 计算警报日期（到期日期 - 警报提前天数）
            if product.alert_time and lot.expiration_date:
                lot.alert_date = expiration_date - relativedelta(days=product.alert_time)
            else:
                lot.alert_date = False

    # 重写write方法确保手动更新时触发计算
    def write(self, vals):
        res = super(StockLot, self).write(vals)
        if 'production_date' in vals:
            self._compute_expiry_dates()
        return res

    # 添加onchange方法（界面即时更新）
    @api.onchange('production_date')
    def _onchange_production_date(self):
        self._compute_expiry_dates()
